<template>
  <div class="chat-container" :class="{ 'elderly-mode': elderlyModeEnabled }">
    <div class="chat-header">
      <van-nav-bar
        title="聊天"
        left-text="配置"
        right-text="历史"
        @click-left="goToSettings"
        @click-right="goToHistory"
      />
    </div>
    
    <div class="chat-messages" ref="messagesContainer">
      <div v-if="messages.length === 0" class="empty-chat">
        <p>开始与AI对话吧</p>
      </div>
      
      <div v-else class="message-list">
        <div 
          v-for="(message, index) in messages" 
          :key="index"
          :class="['message-item', message.role === 'user' ? 'user-message' : 'ai-message']"
        >
          <!-- AI头像 -->
          <div v-if="message.role === 'assistant'" class="avatar">
            <div class="avatar-icon">
              <van-icon name="chat-o" size="20" />
            </div>
          </div>
          
          <div class="message-wrapper">
            <!-- 深度思考标识 -->
            <div v-if="message.role === 'assistant' && deepThinkingEnabled" class="thinking-indicator">
              <div class="thinking-icon">
                <van-icon name="bulb-o" />
              </div>
              <span>已深度思考 (用时 1 秒)</span>
              <van-icon name="arrow" />
            </div>
            
            <div class="message-content">
              <p>{{ message.content }}</p>
            </div>
            
            <!-- 用户消息添加操作按钮区域 -->
            <div v-if="message.role === 'user'" class="message-actions user-actions">
              <van-button 
                type="default" 
                @click="resendMessage(message.content)"
                class="action-btn refresh-btn"
                size="small"
                icon="replay"
              >
                重新提问
              </van-button>
            </div>
            
            <div v-if="message.role === 'assistant'" class="message-actions">
              <van-button 
                type="primary" 
                @click="copyMessage(message.content)"
                class="action-btn copy-btn"
                size="small"
                icon="notes-o"
              >
                复制
              </van-button>
              <van-button 
                type="success" 
                @click="quoteMessage(message.content)"
                class="action-btn quote-btn"
                size="small"
                icon="back-top"
              >
                引用
              </van-button>
              <van-button 
                type="default" 
                @click="showMessageDetails(message)"
                class="action-btn detail-btn"
                size="small"
                icon="info-o"
              >
                详情
              </van-button>
            </div>
          </div>
        </div>
      </div>
      
      <div v-if="isLoading" class="loading-indicator">
        <van-loading type="spinner" color="#1989fa" />
      </div>
    </div>
    
    <div class="chat-input">
      <div class="model-info" @click="openModelSelector">
        <span class="current-model">当前模型: {{ currentModelName }}</span>
        <van-icon name="arrow-down" />
        <span v-if="hasDeepThinking" class="deep-thinking-tag">
          <van-switch v-model="deepThinkingEnabled" size="20" @click.stop />
          <span @click.stop>深度思考</span>
        </span>
      </div>
      
      <div class="input-wrapper">
        <!-- 引用内容显示区域 -->
        <div v-if="hasQuote" class="quote-preview">
          <div class="quote-content">
            <div v-html="formatQuotePreview()"></div>
          </div>
          <van-icon name="cross" class="quote-delete" @click="removeQuote" />
        </div>
        
        <van-field
          v-model="inputMessage"
          type="textarea"
          placeholder="给 DeepSeek 发送消息"
          rows="1"
          autosize
          @keypress.enter.prevent="sendMessage"
        />
      </div>
      
      <div class="input-actions">
        <van-button 
          type="default" 
          size="normal"
          icon="plus"
          @click="startNewChat"
          class="new-chat-btn"
        >
          开启新对话
        </van-button>
        
        <van-button 
          type="primary" 
          size="normal"
          class="send-btn"
          :loading="isLoading"
          :disabled="!inputMessage.trim() || isLoading"
          @click="sendMessage"
        >
          <van-icon name="envelop-o" size="18" /> 发送
        </van-button>
      </div>
    </div>
    
    <!-- 模型选择弹窗 -->
    <van-action-sheet
      v-model:show="showModelSelector"
      title="选择AI模型"
      :closeable="true"
      close-icon="cross"
      @close="closeModelSelector"
    >
      <div class="model-list">
        <div 
          v-for="model in enabledModels" 
          :key="model.id" 
          class="model-item"
          :class="{ 'active': currentModelId === model.id }"
          @click="selectModel(model.id)"
        >
          <div class="model-item-info">
            <span class="model-name">{{ model.name }}</span>
            <span v-if="model.hasDeepThinking" class="feature-tag">支持深度思考</span>
          </div>
          <van-icon v-if="currentModelId === model.id" name="success" color="#1989fa" />
        </div>
      </div>
    </van-action-sheet>
    
    <!-- 消息详情弹窗 -->
    <van-popup
      v-model:show="showMessageDetail"
      round
      position="bottom"
      :style="{ height: '30%' }"
    >
      <div class="message-detail-container">
        <div class="message-detail-header">
          <h3>回复详情</h3>
          <van-icon name="cross" @click="closeMessageDetail" />
        </div>
        <div class="message-detail-content">
          <div class="detail-item">
            <span class="detail-label">模型:</span>
            <span class="detail-value">{{ detailInfo.modelName }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">时间:</span>
            <span class="detail-value">{{ detailInfo.time }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">总Tokens:</span>
            <span class="detail-value">{{ detailInfo.tokens }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">响应时间:</span>
            <span class="detail-value">{{ detailInfo.responseTime }} 毫秒</span>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useChatStore } from '../store/chat'
import { storeToRefs } from 'pinia'
import type { AIModel } from '../store/chat'

const route = useRoute()
const router = useRouter()
const chatStore = useChatStore()
const { 
  currentSession, 
  availableModels,
  enabledModels,
  isLoading, 
  deepThinkingEnabled,
  elderlyModeEnabled,
  currentMessages
} = storeToRefs(chatStore)

const inputMessage = ref('')
const messagesContainer = ref<HTMLElement | null>(null)
const defaultModelId = 'deepseek-v3'
const showModelSelector = ref(false)
const quoteContent = ref('')
const quoteModel = ref('')
const showMessageDetail = ref(false)
const detailInfo = ref({
  modelName: '',
  time: '',
  tokens: 0,
  promptTokens: 0,
  completionTokens: 0,
  responseTime: 0
})

// 获取当前模型ID
const currentModelId = computed(() => currentSession.value?.model || defaultModelId)

// 获取当前模型名称
const currentModelName = computed(() => {
  const model = availableModels.value.find(m => m.id === currentModelId.value)
  return model ? model.name : 'DeepSeek'
})

// 是否支持深度思考
const hasDeepThinking = computed(() => {
  const model = availableModels.value.find(m => m.id === currentModelId.value)
  return model?.hasDeepThinking || false
})

// 消息列表
const messages = computed(() => currentMessages.value)

// 格式化时间
function formatTime(timestamp: number): string {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit'
  })
}

// 前往历史记录页面
function goToHistory() {
  router.push('/history')
}

// 前往设置页面
function goToSettings() {
  router.push('/settings')
}

// 滚动到底部
function scrollToBottom() {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 监听消息变化，自动滚动到底部
watch(() => currentMessages.value.length, () => {
  scrollToBottom()
})

// 监听isLoading变化，当加载完成后滚动到底部
watch(() => isLoading.value, (newValue, oldValue) => {
  // 当从加载状态变为非加载状态时（AI回复完成）
  if (oldValue === true && newValue === false) {
    scrollToBottom()
  }
})

// 检查是否有引用内容
const hasQuote = computed(() => {
  return quoteContent.value !== '';
});

// 格式化引用预览
function formatQuotePreview(): string {
  if (quoteModel.value && quoteContent.value) {
    return `<div class="quote-body">引用自 <span class="quote-model">${quoteModel.value}</span>: ${quoteContent.value}</div>`;
  }
  return '';
}

// 发送消息
async function sendMessage() {
  if (!inputMessage.value.trim() && !hasQuote.value || isLoading.value) return
  
  // 如果没有当前会话，创建一个新会话
  if (!currentSession.value) {
    chatStore.createNewSession(currentModelId.value)
  }
  
  let message = inputMessage.value
  
  // 如果有引用内容，添加到消息前面
  if (hasQuote.value) {
    message = `引用自 ${quoteModel.value} 的回复: "${quoteContent.value}"\n\n${message}`;
    // 发送后清空引用
    quoteModel.value = '';
    quoteContent.value = '';
  }
  
  inputMessage.value = ''
  
  await chatStore.sendMessage(message)
  
  // 滚动到底部
  scrollToBottom()
}

// 复制消息
function copyMessage(content: string) {
  navigator.clipboard.writeText(content)
    .then(() => {
      // 可以添加一个提示
      alert('已复制到剪贴板')
    })
    .catch(err => {
      console.error('复制失败:', err)
    })
}

// 引用消息
function quoteMessage(content: string) {
  // 提取内容的第一行或前20个字符作为引用
  let quotedContent = content.trim();
  if (quotedContent.includes('\n')) {
    quotedContent = quotedContent.split('\n')[0];
  }
  if (quotedContent.length > 20) {
    quotedContent = quotedContent.substring(0, 20) + '...';
  }
  
  // 设置引用内容和模型
  quoteModel.value = currentModelName.value;
  quoteContent.value = quotedContent;
  
  // 聚焦输入框
  const textarea = document.querySelector('.chat-input textarea')
  if (textarea) {
    (textarea as HTMLTextAreaElement).focus()
  }
}

// 删除引用内容
function removeQuote() {
  // 清空引用内容
  quoteModel.value = '';
  quoteContent.value = '';
  
  // 聚焦输入框
  const textarea = document.querySelector('.chat-input textarea')
  if (textarea) {
    (textarea as HTMLTextAreaElement).focus()
  }
}

// 开始新对话
function startNewChat() {
  chatStore.createNewSession(currentModelId.value)
  scrollToBottom()
}

// 选择模型
function selectModel(modelId: string) {
  if (modelId !== currentModelId.value && currentSession.value) {
    // 更新当前会话的模型，而不是创建新会话
    currentSession.value.model = modelId;
    // 更新会话的更新时间
    currentSession.value.updatedAt = Date.now();
    // 保存到本地存储
    chatStore.saveToLocalStorage();
  }
  closeModelSelector();
}

// 打开模型选择弹窗
function openModelSelector() {
  showModelSelector.value = true
}

// 关闭模型选择弹窗
function closeModelSelector() {
  showModelSelector.value = false
}

// 添加重新发送消息的方法
function resendMessage(content: string) {
  // 如果正在加载，不允许重新发送
  if (isLoading.value) return
  
  // 设置输入框内容为要重新发送的消息
  inputMessage.value = content
  
  // 发送消息
  sendMessage()
}

// 格式化详细时间
function formatDetailTime(timestamp: number): string {
  if (!timestamp) return '未知时间'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', { 
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit', 
    minute: '2-digit',
    second: '2-digit'
  })
}

// 显示消息详情
function showMessageDetails(message: any) {
  const model = availableModels.value.find(m => m.id === currentModelId.value)
  detailInfo.value = {
    modelName: model ? model.name : 'DeepSeek',
    time: formatDetailTime(message.timestamp || Date.now()),
    tokens: message.tokens || 0,
    promptTokens: message.promptTokens || 0,
    completionTokens: message.completionTokens || 0,
    responseTime: message.responseTime || 0
  }
  showMessageDetail.value = true
}

// 关闭消息详情弹窗
function closeMessageDetail() {
  showMessageDetail.value = false
}

onMounted(() => {
  // 初始化
  chatStore.init()
  
  // 如果没有当前会话，创建一个新会话使用默认模型
  if (!currentSession.value) {
    chatStore.createNewSession(defaultModelId)
  }
  
  // 初始滚动到底部
  scrollToBottom()
  
  // 使用MutationObserver监听消息容器的变化
  nextTick(() => {
    if (messagesContainer.value) {
      const observer = new MutationObserver(() => {
        scrollToBottom()
      })
      
      observer.observe(messagesContainer.value, {
        childList: true,
        subtree: true,
        characterData: true
      })
    }
  })
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f7f7f7;
}

.chat-header {
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.empty-chat {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #999;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.message-item {
  max-width: 85%;
  display: flex;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.ai-message {
  align-self: flex-start;
}

.message-wrapper {
  display: flex;
  flex-direction: column;
}

.thinking-indicator {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  padding: 6px 12px;
  border-radius: 16px;
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
  align-self: flex-start;
}

.thinking-icon {
  margin-right: 4px;
  color: #1989fa;
}

.avatar {
  align-self: flex-start;
  margin-right: 8px;
}

.avatar-icon {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #e8f0fe;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #1989fa;
}

.message-content {
  padding: 12px 16px;
  border-radius: 18px;
  word-break: break-word;
  position: relative;
}

.user-message .message-content {
  background-color: #e1f3ff;
  border-bottom-right-radius: 4px;
  margin-left: auto;
}

.ai-message .message-content {
  background-color: #fff;
  border-bottom-left-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.message-content p {
  margin: 0;
  white-space: pre-wrap;
  line-height: 1.5;
}

.message-actions {
  display: flex;
  gap: 12px;
  margin-top: 12px;
  align-self: flex-start;
}

.user-actions {
  align-self: flex-end;
}

.action-btn {
  padding: 0 12px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 16px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
  color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-btn:active {
  transform: scale(0.96);
}

.action-btn span {
  margin-left: 6px;
}

.copy-btn {
  background-color: #1989fa;
}

.copy-btn:hover {
  opacity: 0.9;
}

.quote-btn {
  background-color: #07c160;
}

.quote-btn:hover {
  opacity: 0.9;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  align-self: flex-end;
}

.loading-indicator {
  display: flex;
  justify-content: center;
  margin: 16px 0;
}

.chat-input {
  padding: 12px 16px;
  background-color: #fff;
  border-top: 1px solid #eee;
}

.model-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 8px;
  cursor: pointer;
}

.current-model {
  font-size: 14px;
  color: #333;
  margin-right: 5px;
}

.deep-thinking-tag {
  display: flex;
  align-items: center;
  margin-left: auto;
  font-size: 14px;
  color: #666;
}

.deep-thinking-tag span {
  margin-left: 5px;
}

.input-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 12px;
  background-color: #f5f7fa;
  border-radius: 20px;
  padding: 4px 12px;
}

.quote-preview {
  width: 100%;
  position: relative;
  background-color: #f2f2f2;
  border-radius: 8px;
  padding: 10px 12px;
  margin-bottom: 8px;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.quote-content {
  flex: 1;
  overflow: hidden;
}

.quote-body {
  color: #666;
  font-size: 14px;
  line-height: 1.4;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.quote-model {
  color: #1989fa;
  font-weight: 500;
}

.quote-delete {
  padding: 4px;
  color: #999;
  cursor: pointer;
  margin-left: 8px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.05);
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quote-delete:hover {
  color: #ff4d4f;
  background-color: rgba(255, 77, 79, 0.1);
}

.input-wrapper :deep(.van-field__control) {
  background-color: transparent;
  min-height: 36px;
}

.input-tools {
  display: none;
}

.input-actions {
  display: flex;
  justify-content: space-between;
}

/* 模型选择弹窗样式 */
.model-list {
  padding: 16px;
  max-height: 60vh;
  overflow-y: auto;
}

.model-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.model-item:last-child {
  border-bottom: none;
}

.model-item.active {
  background-color: rgba(25, 137, 250, 0.05);
}

.model-item-info {
  display: flex;
  flex-direction: column;
}

.model-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 4px;
}

.feature-tag {
  display: inline-block;
  background-color: #e8f0fe;
  color: #1989fa;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  align-self: flex-start;
}

.new-chat-btn,
.send-btn {
  height: 40px;
  font-size: 16px;
  padding: 0 20px;
  border-radius: 20px;
}

.send-btn {
  min-width: 100px;
}

.refresh-btn {
  background-color: #f2f2f2;
  color: #666;
  border: 1px solid #e0e0e0;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.refresh-btn:hover {
  background-color: #e8e8e8;
  color: #333;
}

.detail-btn {
  background-color: #5cadff;
}

.detail-btn:hover {
  opacity: 0.9;
}

.message-detail-container {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.message-detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
  margin-bottom: 16px;
}

.message-detail-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.message-detail-content {
  flex: 1;
  overflow-y: auto;
}

.detail-item {
  display: flex;
  margin-bottom: 12px;
  font-size: 16px;
}

.detail-label {
  width: 80px;
  color: #666;
}

.detail-value {
  flex: 1;
  color: #333;
  font-weight: 500;
}

@media (max-width: 768px) {
  .message-item {
    max-width: 90%;
  }
}

/* 适老化模式特定样式 */
.elderly-mode .message-content {
  padding: 16px 20px;
  border-radius: 20px;
}

.elderly-mode .message-content p {
  font-size: 18px;
  line-height: 1.6;
}

.elderly-mode .action-btn {
  padding: 0 16px;
  height: 40px;
  border-radius: 20px;
  font-size: 16px;
}

.elderly-mode .model-info {
  padding: 12px 16px;
}

.elderly-mode .current-model {
  font-size: 16px;
}

.elderly-mode .input-wrapper {
  border-radius: 24px;
  padding: 8px 16px;
}

.elderly-mode .quote-preview {
  padding: 14px 16px;
  border-radius: 12px;
  font-size: 16px;
}

.elderly-mode .quote-body {
  font-size: 16px;
  line-height: 1.5;
}

.elderly-mode .new-chat-btn,
.elderly-mode .send-btn {
  height: 48px;
  font-size: 18px;
  padding: 0 24px;
  border-radius: 24px;
}

.elderly-mode .message-detail-header h3 {
  font-size: 22px;
}

.elderly-mode .detail-item {
  font-size: 18px;
  margin-bottom: 16px;
}

.elderly-mode .detail-label {
  width: 100px;
}
</style> 